package com.jd.opendj.api.client;

import com.google.gson.Gson;
import com.jd.opendj.api.OpenDjClient;
import com.jd.opendj.api.OpenDjResponse;
import com.jd.opendj.api.exception.FailedRequestException;
import com.jd.opendj.api.OpenDjRequest;
import com.jd.opendj.api.util.HttpUtil;

/**
 * <p>AutoRetryOpenDjClient</p>
 * description
 *
 * @author 邓峰峰
 * @date 9/2/2020 8:12 PM
 */
public class DefaultOpenDjClient implements OpenDjClient {

    /**
     *sample value:是
     *采用OAuth授权方式为必填参数
     */
    protected String token ;
    /**
     *sample value:是
     *应用的app_key
     */
    protected String appKey ;

    /**
     * secret
     */
    protected String secret;



    public DefaultOpenDjClient(String appKey, String appSecret,String token) {
        this.appKey = appKey;
        this.secret = appSecret;
        this.token =token;
    }

    @Override
    public <T extends OpenDjResponse> T execute(OpenDjRequest<T> request) throws FailedRequestException {
        if (request == null) {
            throw new IllegalArgumentException("必要参数request不可为空");
        }
        String result = HttpUtil.sendSimplePostRequest(request.api().getUrl(), request.createParams(appKey,secret,token));
        final Gson gson = new Gson();
        final T t = gson.fromJson(result, request.getResponseClass());
        //如果请求失败
        if(!t.getSuccess()){
            throw new FailedRequestException(t.getMsg());
        }
        //转换成java对象
        t.toJavaObject();
        return t;

    }
}
